<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Postalapi\Postal;
use App\Http\Controllers\ScoreRuleController;
use App\Models\BookHomeDeliverAddress;
use App\Models\BookHomeOrder;
use App\Models\BookHomeOrderAddress;
use App\Models\BookHomeOrderBook;
use App\Models\BookHomeOrderRefund;
use App\Models\BookHomePostalRev;
use App\Models\BookHomePurchase;
use App\Models\BookHomeReturnAddress;
use App\Models\BookHomeSchoolbag;
use App\Models\Shop;
use App\Models\ShopBook;
use App\Models\UserLibraryInfo;
use App\Models\UserWechatInfo;
use App\Validate\BookHomeNewBookValidate;
use Exception;
use Illuminate\Support\Facades\DB;


/**
 * 图书到家 新书采购清单（书店端）
 * Class NewBookRecom
 * @package app\api\controller
 */
class BookHomeNewBookShopController extends CommonController
{
    private $model = null;
    private $bookHomeOrderBookModel = null;
    private $bookHomePurchaseModel = null;
    private $shopBookModel = null;
    private $validate = null;
    public $score_type = 17;

    public function __construct()
    {
        parent::__construct();
        $this->model = new BookHomeOrder();
        $this->bookHomeOrderBookModel = new BookHomeOrderBook();
        $this->bookHomePurchaseModel = new BookHomePurchase();
        $this->shopBookModel = new ShopBook();
        $this->validate = new BookHomeNewBookValidate();
    }


    /**
     * 申请列表、发货列表、所有订单列表 （新书）
     * @param is_pay  类型  2 已支付  5 .已退款  6.已同意（后台单纯同意）
     *              7 已拒绝（后台单纯同意）  8已发货（数据就增加到用户采购列表）
     *              9 无法发货   固定参数 申请列表 2   发货列表 6  所有订单列表 5789
     * @param start_time 申请开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 申请结束时间     数据格式    2020-05-12 12:00:00
     * @param keywords_type 检索key  0 全部 1 订单号 2 读者证号 3 收件人姓名  4 收件人电话
     * @param keywords 检索值
     * @param shop_id 书店id   不传  或转空  或 0，表示全部
     * @param page  页数默认为 1
     * @param limit  条数 默认 10 条
     */
    public function orderList()
    {
        //处理已失效的订单
        BookHomeOrder::checkNoPayOrder();

        //增加验证场景进行验证
        if (!$this->validate->scene('order_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $is_pay = $this->request->is_pay;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $keywords_type = $this->request->keywords_type;
        $keywords = $this->request->keywords;
        $shop_id = $this->request->shop_id;
        $page = intval($this->request->page, 1) ?: 1;
        $limit = intval($this->request->limit, 1) ?: 10;

        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id)) {
            return $this->returnApi(203, '暂无数据'); //无权限访问
        }

        $res = $this->model->lists(null, 1, $is_pay, $shop_id, $keywords, $keywords_type, $start_time, $end_time, $shop_all_id, $limit);

        if ($res['data']) {
            $bookHomePostalRevModel = new BookHomePostalRev();

            foreach ($res['data'] as $key => $val) {
                //读者证号信息
                $res['data'][$key]['reader_info']['account'] = $val['account'];
                $res['data'][$key]['reader_info']['username'] = $val['username'];
                unset($res['data'][$key]['account'], $res['data'][$key]['username']);

                $res['data'][$key]['shop_info']['shop_name'] = $val['shop_name'];
                unset($res['data'][$key]['shop_name']);

                $res['data'][$key]['order_info']['id'] = $val['id'];
                $res['data'][$key]['order_info']['is_pay'] = $val['is_pay'];
                $res['data'][$key]['order_info']['order_number'] = $val['order_number'];
                $res['data'][$key]['order_info']['create_time'] = $val['create_time'];
                unset($res['data'][$key]['is_pay'], $res['data'][$key]['order_number'], $res['data'][$key]['create_time'], $res['data'][$key]['id']);

                $res['data'][$key]['order_info']['time'] = $this->shopBookModel->getStateNameAndTime($val)['time']; //各种事件的集合

                $res['data'][$key]['address_info']['tracking_number'] = $val['tracking_number']; //快递单号
                $res['data'][$key]['address_info']['username'] = $val['address_username'];
                $res['data'][$key]['address_info']['tel'] = $val['tel'];
                $res['data'][$key]['address_info']['province'] = $val['province'];
                $res['data'][$key]['address_info']['city'] = $val['city'];
                $res['data'][$key]['address_info']['district'] = $val['district'];
                $res['data'][$key]['address_info']['street'] = $val['street'];
                $res['data'][$key]['address_info']['address'] = $val['address'];
                unset($res['data'][$key]['address_username']);
                unset($res['data'][$key]['tel']);
                unset($res['data'][$key]['province']);
                unset($res['data'][$key]['city']);
                unset($res['data'][$key]['district']);
                unset($res['data'][$key]['street']);
                unset($res['data'][$key]['address']);
                $book_id = $this->bookHomeOrderBookModel->where('order_id', $val['id'])->pluck('book_id');
                $res['data'][$key]['book_info'] = $this->shopBookModel
                    ->select('id', 'book_name', 'author', 'author', 'press', 'pre_time', 'isbn', 'price', 'book_selector', 'rack_type', 'rack_describe', 'rack_code')
                    ->whereIn('id', $book_id)
                    ->get()
                    ->toArray();

                //匹配生成的条形码
                if (stripos($is_pay, '8') !== false || stripos($is_pay, '6') !== false) {
                    foreach ($res['data'][$key]['book_info'] as $k => $v) {
                        $res['data'][$key]['book_info'][$k]['barcode'] = $this->bookHomePurchaseModel->getBarcode($v['id'], $val['id'], $val['account_id']);
                    }
                } else {
                    foreach ($res['data'][$key]['book_info'] as $k => $v) {
                        $res['data'][$key]['book_info'][$k]['barcode'] = '';
                    }
                }
                $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);

                //获取运单轨迹
                if (!empty($val['tracking_number'])) {
                    $res['data'][$key]['track'] = $bookHomePostalRevModel->getTrack($val['tracking_number']);
                } else {
                    $res['data'][$key]['track'] = null;
                }
            }
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }


    /**
     * 获取未处理订单 和未发货订单数量 (新书)
     * @param shop_id 书店id，不传表示自己管辖的所有书店
     */
    public function getOrderNumber()
    {
        $shop_id = $this->request->shop_id;
        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id) || ($shop_id && !in_array($shop_id, $shop_all_id))) {
            return $this->returnApi(202, '您无权操作此书店数据'); //无权限访问
        }

        //获取未处理订单数量
        $data['untreated_number'] = $this->model->getOrderNumber(1, 2, $shop_id, $shop_all_id);
        //获取未发货订单数量
        $data['undeliver_number'] = $this->model->getOrderNumber(1, 6, $shop_id, $shop_all_id);
        //获取其他订单数量
        $data['other_order_number'] = $this->model->getOrderNumber(1, [5, 7, 8, 9], $shop_id, $shop_all_id);

        return $this->returnApi(200, '获取成功', true, $data);
    }

    /**
     * 获取订单详情
     * @param order_id  订单id
     */
    public function orderDetail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('order_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id)) {
            return $this->returnApi(203, '暂无数据'); //无权限访问
        }
        $order_id = $this->request->order_id;
        $res = $this->model->detail($order_id);

        if ($res) {
            //组装数据
            $res = $res->toArray();
            $data = $this->model->checkOrderData($res);
            $data['book_info'] = $this->bookHomeOrderBookModel->getOrderBookInfoList($order_id, $res);

            //获取运单轨迹
            if (!empty($res['tracking_number'])) {
                $bookHomePostalRevModel = new BookHomePostalRev();
                $data['track'] = $bookHomePostalRevModel->getTrack($res['tracking_number']);
            } else {
                $data['track'] = null;
            }

            return $this->returnApi(200, '获取成功', true, $data);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 管理员同意 和拒绝用户的 采购申请
     * @param order_ids  订单id  多个 , 逗号拼接
     * @param state   1 同意  2 拒绝
     * @param remark   拒绝理由
     */
    public function disposeOrderApply()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('dispose_order_apply')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $order_ids = $this->request->order_ids;
        $state = $this->request->state;
        $remark = $this->request->remark;

        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id)) {
            return $this->returnApi(203, '暂无数据'); //无权限访问
        }

        $order_ids = explode(',', $order_ids);
        DB::beginTransaction();
        try {
            if ($state == 1) {
                $is_pay = 6;
                $title = '图书到家：审核通过';
                $intro = '您在书店申请的新书借阅已通过';
            } else {
                $is_pay = 7;
                $title = '图书到家：审核未通过';

                $remarks = empty($remark) ? '' : '拒绝理由为：' . $remark;
                $intro = '您在书店申请的新书借阅未通过；' . $remarks;
            }
            foreach ($order_ids as $key => $val) {
                $order_info = $this->model->find($val);
                if ($order_info['is_pay'] != 2) {
                    throw new Exception('订单号: ' . $order_info['order_number'] . " 数据处理失败");
                }
                $order_info->is_pay = $is_pay;
                $order_info->agree_time = date('Y-m-d H:i:s');
                $order_info->refund_remark = $state == 1 ? '' : $remark;
                $order_info->save();

                if ($state == 2) {
                    $book_id_all = $this->bookHomeOrderBookModel->where('order_id', $order_info['id'])->pluck('book_id');
                    //增加库存
                    foreach ($book_id_all as $v) {
                        $shopBookModel = new ShopBook();
                        $res = $shopBookModel::modifyRepertoryNumber($v, 1);
                        if ($res !== true) {
                            throw new \Exception($res);
                        }
                    }
                }
                //添加系统消息
                $this->systemAdd($title, $order_info->user_id, $order_info->account_id, 39, $order_info->id, $intro);

                //审核拒绝推送模板消息
                if (config('other.is_send_wechat_temp_info')) {
                    if ($state == 2) {
                        //添加推送模板消息
                        $tempInfoObj = new \App\Http\Controllers\TempInfoController();
                        $data['openid'] = UserWechatInfo::getOpenIdByUserId($order_info['user_id']);
                        $data['username'] = UserLibraryInfo::where('id', $order_info['account_id'])->value('username');
                        $data['msg'] = '已拒绝';
                        $data['msg1'] = empty($remark) ? "书籍不存在或其他原因导致！" : $remark;
                        $data['msg2'] = '您在线上申请的书籍，审核未通过，请重新申请其他书籍！';
                        $data['create_time'] = date('Y-m-d H:i:s');

                        $data['link'] = '?booktype=1&id=' . $order_info['id'];
                        $tempInfoObj->sendTempInfoApplyReject($data);
                    }
                }

                if ($state == 2) {
                    //进行退款操作
                    $bookHomeOrderRefundModel = new BookHomeOrderRefund();
                    $bookHomeOrderRefundModel->refund($val, $remarks);
                }
            }

            DB::commit();
            return $this->returnApi(200, '处理成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 确认发货或无法发货
     * @param state   1 确认发货  2 无法发货
     * @param order_id  订单id  只针对单个订单
     * @param username   收件人名称
     * @param tel   收件人电话
     * @param province   收件人省
     * @param city   收件人市
     * @param district   收件人区、县
     * @param street 街道
     * @param address   收件人详细地址
     * @param content   [{"book_id":1,"barcode":"123456","book_num":"索书号"},{"book_id":2,"barcode":"456789","book_num":"索书号"}]  书籍 条形码  json 格式数据
    //* @param tracking_number   确认发货 时必填 订单号
     * @param remark   拒绝理由
     * @param isbns   缺少的书籍isbn号 多个逗号拼接 (前端实际传的数据为： 鲁迅散文诗歌全集 (9787505742734)  )   （无法发货才填）
     */
    public function disposeOrderDeliver()
    {
        /*$data = [
              ['book_id'=>1 , 'barcode'=>'123456' , 'book_num'=>'索书号'],
              ['book_id'=>2 , 'barcode'=>'456789' , 'book_num'=>'索书号'],
          ];*/

        //增加验证场景进行验证
        if (!$this->validate->scene('dispose_order_deliver')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id)) {
            return $this->returnApi(203, '暂无数据'); //无权限访问
        }

        $order_id = $this->request->order_id;
        $state = $this->request->state;
        $username = $this->request->username;
        $tel = $this->request->tel;
        $province = $this->request->province;
        $city = $this->request->city;
        $district = $this->request->district;
        $street = $this->request->street;
        $address = $this->request->address;
        $remark = $this->request->remark;
        $content = $this->request->content;
        $isbns = $this->request->isbns;
        if ($state == 1 && (empty($username) && empty($tel) && empty($province) && empty($city) && empty($district) && empty($street) && empty($address)) && empty($content)) {
            return $this->returnApi(201, '参数错误');
        }
        if (count(array_column(json_decode($content, true), 'barcode')) != count(array_unique(array_column(json_decode($content, true), 'barcode')))) {
            return $this->returnApi(201, '条形码不能填写相同数据');
        }

        //获取订单所有的书籍id
        $bookHomeOrderBookModel = new BookHomeOrderBook();
        $book_info = $bookHomeOrderBookModel->getOrderBookInfoList($order_id, ['type' => 1]);
        $book_ids = array_column($book_info, 'id');

        $libApi = $this->getLibApiObj();
        if ($state == 1) {
            if (empty($tel) || !verify_tel($tel)) {
                return $this->returnApi(201, '电话号码格式不正确');
            }
            /*检查是否合法地址*/
            $map = $this->getLonLatByAddress($province . $city . $district . $street . $address);
            if (isset($map['code']) && $map['code'] == 202) {
                return $this->returnApi(202, '收货地址有误，请填写正确地址');
            }

            //判断书籍条形码是否填写完整  自己填写
            $book_ids_barcode = array_column(json_decode($content, true), null, 'book_id');

            foreach ($book_ids as $k => $v) {
                //判断条形码前几位是否符合要求
                $new_book_barcode_prefix = config('other.new_book_barcode_prefix');
                $new_book_fixed_barcode = config('other.new_book_fixed_barcode');

                $front_barcode = substr($book_ids_barcode[$v]['barcode'], 0, strlen($new_book_barcode_prefix));
                if ($front_barcode != $new_book_barcode_prefix || strlen($book_ids_barcode[$v]['barcode']) != strlen($new_book_fixed_barcode)) {
                    // dump($front_barcode);
                    // dump($new_book_barcode_prefix);
                    // dump($book_ids_barcode[$v]['barcode']);
                    // dump(strlen($book_ids_barcode[$v]['barcode']));
                    // dump(strlen($new_book_fixed_barcode));
                    return $this->returnApi(202, '条形码规则不正确');
                }

                $lib_book_prefix = config('other.lib_book_prefix');
                $book_ids_barcode[$v]['barcode'] = str_ireplace($lib_book_prefix, '', $book_ids_barcode[$v]['barcode']);

                //索书号可选
                if (!empty($book_ids_barcode[$v]['book_num'])) {
                    $shop_book_info = $this->shopBookModel->find($v);
                    if (empty($shop_book_info->book_num)) {
                        $shop_book_info->book_num = $book_ids_barcode[$v]['book_num'];
                        $shop_book_info->save();
                    }
                }

                if (!isset($book_ids_barcode[$v]['barcode'])) {
                    return $this->returnApi(202, '请完整填写条形码');
                } else {
                    //判断条形码是否存在
                    $barcode_exist = $libApi->getAssetByBarcode($book_ids_barcode[$v]['barcode']);

                    if ($barcode_exist['code'] != 202) {
                        return $this->returnApi(202, '条形码：【' . $book_ids_barcode[$v]['barcode'] . '】已存在');
                    }
                }
            }
        }

        $order_info = $this->model->find($order_id);
        if ($order_info['is_pay'] != 6) {
            return $this->returnApi(201, '网络错误');
        }
        if (empty($order_info)) {
            return $this->returnApi(201, '暂无数据');
        }
        //获取发货地址信息
        $BookHomeReturnAddressModel = new BookHomeReturnAddress();
        $deliver_address = $BookHomeReturnAddressModel->getDeliverAddress(1, $order_info->shop_id);
        if (empty($deliver_address)) {
            return $this->returnApi(201, '发货信息未设置，请先设置');
        }

        DB::beginTransaction();
        try {
            $postalMsg = ''; //失败的消息
            if ($state == 1) {
                //判断用户借阅权限
                $account_info = $this->shopBookModel->checkNewBookBorrowAuth($order_info['account_id'], $book_ids, true);

                //修改用户借阅记录
                $this->bookHomePurchaseModel->insertAccountBorrowMoneyNumber($order_info['account_id'], $book_info);

                //修改订单地址
                $bookHomeOrderAddressModel = new BookHomeOrderAddress();
                $bookHomeOrderAddressModel->changeOrderAddress($order_id, $this->request->all(), $deliver_address);

                $purchase_number = 0; //本次采购本书
                $purchase_money = 0; //本次采购金额

                $pushTempInfoData = []; //推送模板消息数据

                //先获取邮政订单号
                $postalObj = new Postal();
                //收货人地址
                $take_address = [
                    'username' => $username,
                    'tel' => $tel,
                    'province' => $province,
                    'city' => $city,
                    'street' => $street,
                    'district' => $district,
                    'address' => $address,
                ];
                if (config('other.is_write_postal')) {
                    $tracking_info = $postalObj->setOrder($order_id, $deliver_address, $take_address);

                    if ($tracking_info['code'] == 200) {
                        $tracking_number = $tracking_info['data']['waybill_no'];
                    } else {
                        throw new Exception($tracking_info['msg']);
                        // $postalMsg = '快递下单失败，请再次手动下单';
                    }
                } else {
                    $tracking_number = null;
                }

                $order_info->tracking_number = $tracking_number;
                $order_info->is_pay = 8;
                //获取邮政订单号end

                foreach ($book_info as $key => $val) {
                    /*自主获取条形码2  if($key !== 0){
                        $barcode = $this->newOrderModelObj->getBarcode($barcode , false);//手动递增
                    }*/

                    $barcode = $book_ids_barcode[$val['id']]['barcode'];
                    //书籍先写入,有可能成功，有可能失败
                    $res = $libApi->addCirMarcAndAcqWorkAndAssetAndBorrowBook($val, $barcode, $account_info['account']);

                    //不管失败成功都要写入用户记录
                    if ($res['code'] !== 200) {
                        if ($key === 0) {
                            //throw new \Exception('服务器接口，数据处理失败');//第一个失败就全部失败
                            throw new \Exception($res['msg']); //第一个失败就全部失败
                        }
                        $where['node'] = 2;
                        $where['expire_time'] = date('Y-m-d H:i:s', strtotime("+1 month")); //默认一个月
                    } else {
                        //修改条形码对应的记录为成功；
                        $where['node'] = 1;
                        //TODO
                        $where['expire_time'] = $res['content']['returnDate'];
                    }

                    //修改条形码对应的记录为失败或成功；
                    $this->bookHomeOrderBookModel->where('order_id', $order_id)->where('book_id', $val['id'])->update([
                        'node' => $where['node'],
                        'change_time' => date('Y-m-d H:i:s'),
                    ]);

                    $where['create_time'] = date('Y-m-d H:i:s');
                    $where['return_state'] = 1;
                    $where['settle_state'] = 3;

                    $where['barcode'] = $barcode;
                    $where['book_id'] = $val['id'];
                    $where['user_id'] = $order_info['user_id'];
                    $where['account_id'] = $order_info['account_id'];
                    $where['shop_id'] = $order_info['shop_id'];
                    $where['order_id'] = $order_id;
                    $where['price'] = $val['price'];
                    $where['isbn'] = $val['isbn'];
                    $where['type'] = 1;
                    $where['pur_manage_id'] = $this->request->manage_id;
                    $this->bookHomePurchaseModel->insert($where);

                    $pushTempInfoData[$key]['book_name'] = $val['book_name'];
                    $pushTempInfoData[$key]['author'] = $val['author'];
                    $pushTempInfoData[$key]['create_time'] = $where['create_time'];
                    $pushTempInfoData[$key]['expire_time'] = $where['expire_time'];

                    $purchase_number++;
                    $purchase_money += $val['price'];

                    //相应数据从书袋清除,馆藏书还可以再次借阅，新书不能
                    BookHomeSchoolbag::where('book_id', $val['id'])->where('type', 1)->where('user_id', $order_info['user_id'])->delete();
                }

                //增加书店采购金额
                $shop_info = Shop::where('id', $order_info['shop_id'])->first();
                $shop_info->purchase_number = $shop_info->purchase_number + $purchase_number;
                $shop_info->purchase_money = sprintf("%.2f", $shop_info->purchase_money + $purchase_money);
                $shop_info->save();



                $title = '图书到家：采购已发货';
                $intro = '您在书店申请借阅的新书已发货，请及时关注邮递信息';


                //添加推送模板消息
                // $tempInfoObj = new \app\common\controller\TempInfo();
                // $data['openid'] = \app\common\controller\Common::getOpenIdByUserId($order_info['user_id']);
                // $data['msg'] = '请随时关注邮递进度！';

                // foreach ($pushTempInfoData as $key => $val) {
                //     $data['book_name'] = $val['book_name'];
                //     $data['author'] = $val['author'];
                //     $data['create_time'] = $val['create_time'];
                //     $data['expire_time'] = $val['expire_time'];

                //     $tempInfoObj->sendTempInfoBorrowSuccess($data);
                // }
            } else {
                //缺少的书籍id
                $lack_book_msg = '';
                if (!empty($isbns)) {
                    $isbns = explode(',', $isbns);
                    $isbns_msg = '';
                    foreach ($isbns as $val) {
                        $isbns_msg .= ',' . '[' . $val . ']';
                    }
                    $lack_book_msg = trim($isbns_msg, ',');
                }

                $order_info->is_pay = 9;
                $order_info->refund_remark = $remark . $lack_book_msg;

                $title = '图书到家：采购发货失败';
                $remarks = empty($remark) ? '' : '失败原因：' . $remark . ';';
                $intro = '您在书店申请借阅的新书发货失败 ' . $remarks . $lack_book_msg;

                //增加库存
                foreach ($book_ids as $v) {
                    $shopBookModel = new ShopBook();
                    $res = $shopBookModel::modifyRepertoryNumber($v, 1);
                    if ($res !== true) {
                        throw new \Exception($res);
                    }
                }

                //添加推送模板消息
                if (config('other.is_send_wechat_temp_info')) {
                    $tempInfoObj = new \App\Http\Controllers\TempInfoController();
                    $data['openid'] = UserWechatInfo::getOpenIdByUserId($order_info['user_id']);
                    $data['username'] = UserLibraryInfo::where('id', $order_info['account_id'])->value('username');
                    $data['msg'] = $title;
                    $data['msg1'] = empty($remark) ? "书籍不存在或其他原因导致！" : $remark;
                    $data['msg1'] =  $data['msg1'] . $lack_book_msg;
                    $data['msg2'] = '您在线上申请的馆藏书籍发货失败，请重新申请其他书籍！';
                    $data['create_time'] = date('Y-m-d H:i:s');

                    $data['link'] = '?booktype=1&id=' . $order_info['id'];
                    $tempInfoObj->sendTempInfoApplyReject($data);
                }
                //进行退款操作
                $msg = empty($remark) ? "书籍不存在或其他原因导致！" : $remark;
                $bookHomeOrderRefundModel = new BookHomeOrderRefund();
                $res = $bookHomeOrderRefundModel->refund($order_id, $msg);
            }



            $order_info->deliver_time = date('Y-m-d H:i:s');
            $order_info->deliver_manage_id = $this->request->manage_id;
            $order_info->save();

            //添加系统消息
            $system_id = $this->systemAdd($title, $order_info->user_id, $order_info->account_id, 40, $order_info->id, $intro);

            if ($state == 1) {
                //判断积分是否满足条件
                if (config('other.is_need_score') === true) {
                    $scoreRuleObj = new ScoreRuleController();
                    $score_status = $scoreRuleObj->checkScoreStatus($this->score_type, $order_info->user_id,  $order_info->account_id);
                    if ($score_status['code'] == 202 || $score_status['code'] == 203) {
                        throw new Exception($score_status['msg']); //'积分不足无法参加活动'
                    } elseif ($score_status['code'] == 200) {
                        $scoreRuleObj->scoreChange($score_status, $order_info->user_id,  $order_info->account_id, $system_id); //添加积分消息
                    }
                }
            }

            DB::commit();
            return $this->returnApi(200, '处理成功' . $postalMsg, true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 针对邮递发货 获取运单号失败后，补发获取快递单号（新书）
     * @param order_id  订单id  只针对单个订单
     */
    public function againGetTrackingNumberShop()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('again_get_tracking_number_shop')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $order_id = $this->request->order_id;
        $order_info = $this->model->find($order_id);
        if (!empty($order_info->tracking_number)) {
            return $this->returnApi(202, '此订单已发货，不能再次获取');
        }
        //获取发货地址信息
        // $bookHomeDeliverAddressModel = new BookHomeDeliverAddress();
        // $deliver_address = $bookHomeDeliverAddressModel->getPostalAddressInfoByShopId($order_info->shop_id);
        $bookHomeReturnAddressModel = new BookHomeReturnAddress();
        $deliver_address = $bookHomeReturnAddressModel->getDeliverAddress(1, $order_info->shop_id);

        //获取收货地址信息
        $bookHomeOrderAddressModel = new BookHomeOrderAddress();
        $take_address = $bookHomeOrderAddressModel->getOrderAddress($order_id);

        $postalObj = new Postal();
        $tracking_info = $postalObj->setOrder($order_id, $deliver_address, $take_address);
        if ($tracking_info['code'] == 200) {
            $tracking_number = $tracking_info['data']['waybill_no'];
            $order_info->tracking_number = $tracking_number;
            $res = $order_info->save();
            if ($res) {
                return $this->returnApi(200, '快递单号获取成功', true);
            } else {
                return $this->returnApi(202, '快递下单失败，请稍后重试');
            }
        } else {
            return $this->returnApi(202, '快递下单失败，请稍后重试');
        }
    }

    /**
     * 打印电子面单 （新书）
     * @param order_id  订单id  只针对单个订单
     */
    public function printExpressSheetShop()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('print_express_sheet_shop')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $order_id = $this->request->order_id;
        $order_info = $this->model->find($order_id);

        //获取发货地址信息
        // $bookHomeDeliverAddressModel = new BookHomeDeliverAddress();
        // $deliver_address = $bookHomeDeliverAddressModel->getPostalAddressInfoByShopId($order_info->shop_id);

        $bookHomeReturnAddressModel = new BookHomeReturnAddress();
        $deliver_address = $bookHomeReturnAddressModel->getDeliverAddress(1, $order_info->shop_id);

        //获取收货地址信息
        $bookHomeOrderAddressModel = new BookHomeOrderAddress();
        $take_address = $bookHomeOrderAddressModel->getOrderAddress($order_id);

        $postalObj = new Postal();
        $print_electronic_sheet_info = $postalObj->printElectronicSheet($order_id, $deliver_address, $take_address);
        $tracking_number = $this->model->where('id', $order_id)->value('tracking_number');
        if ($print_electronic_sheet_info['code'] == 200) {
            $route_code = $print_electronic_sheet_info['data'][0]['routeCode'];
            if ($route_code) {
                return $this->returnApi(200, '获取成功', true, [
                    'route_code' => $route_code,
                    'tracking_number' => $tracking_number,
                    'deliver_address' => $deliver_address,
                    'take_address' => $take_address,
                ]);
            } else {
                return $this->returnApi(202, '获取失败');
            }
        } else {
            return $this->returnApi(202, '获取失败');
        }
    }


    /**
     * 书店采购清单(书店查看)
     * @param shop_id  书店id   0、全部
     * @param keywords_type  检索条件   0、全部  1、书名  2、作者 3 ISBN 4 读者证号 5 条形码 默认 0
     * @param keywords  检索条件
     * @param start_time 发货开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 发货结束时间     数据格式    2020-05-12 12:00:00
     * @param settle_state		结算状态  0、全部 1 已结算  2 结算中  3 未结算
     * @param way		采购方式   1 为 线上荐购 ， 2 为线下荐购
     * @param book_selector  是否套数   不传  或转空  或 0，表示全部  1 是 2 否
     * @param pur_manage_id  采购管理员id  不传  或转空  或 0，表示全部
     * @param settle_sponsor_manage_id  发起结算的管理员id   不传  或转空  或 0，表示全部
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function purchaseList()
    {
        $shop_id = $this->request->shop_id;
        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id) || ($shop_id && !in_array($shop_id, $shop_all_id))) {
            return $this->returnApi(202, '您无权操作此书店'); //无权限访问
        }

        $shop_id = $this->request->shop_id;
        $keywords_type = $this->request->keywords_type;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $settle_state = $this->request->settle_state;
        $book_selector = $this->request->book_selector;
        $way = $this->request->way;
        $pur_manage_id = $this->request->pur_manage_id;
        $settle_sponsor_manage_id = $this->request->settle_sponsor_manage_id;
        $page = intval($this->request->page, 1) ?: 1;
        $limit = intval($this->request->limit, 10) ?: 10;

        $param = [
            'shop_id' => $shop_id,
            'keywords_type' => $keywords_type,
            'keywords' => $keywords,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'settle_state' => $settle_state,
            'book_selector' => $book_selector,
            'way' => $way,
            'pur_manage_id' => $pur_manage_id,
            'settle_sponsor_manage_id' => $settle_sponsor_manage_id,
            'shop_all_id' => $shop_all_id,
            'page' => $page,
            'limit' => $limit,
            'select_way' => 1,
        ];
        //列表
        $res = $this->bookHomePurchaseModel->lists($param);

        //人次
        $param['select_way'] = 2;
        $user_count = $this->bookHomePurchaseModel->lists($param);

        //总金额
        $param['select_way'] = 3;
        $book_price_count = $this->bookHomePurchaseModel->lists($param);

        $res['book_count'] = $res['total']; //书的统计记录等于总个条数
        $res['user_count'] = $user_count;
        $res['book_price_count'] = $book_price_count;

        if ($res['data']) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }
    /**
     * 计算采购数量及结算状态数量
     * @param shop_id  书店id   0、全部
     * @param keywords_type  检索条件   0、全部  1、书名  2、作者 3 ISBN 4 读者证号 5 条形码 默认 0
     * @param keywords  检索条件
     * @param start_time 申请开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 申请结束时间     数据格式    2020-05-12 12:00:00
   //  * @param settle_state		结算状态  0、全部 1 已结算  2 结算中  3 未结算
     * @param way		采购方式   1 为 线上荐购 ， 2 为线下荐购
     * @param book_selector  是否套数   不传  或转空  或 0，表示全部  1 是 2 否
     * @param pur_manage_id  采购管理员id  不传  或转空  或 0，表示全部
     * @param settle_sponsor_manage_id  发起结算的管理员id   不传  或转空  或 0，表示全部
     */
    public function getPurchaseNumber()
    {
        $shop_id = $this->request->shop_id;
        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id) || ($shop_id && !in_array($shop_id, $shop_all_id))) {
            return $this->returnApi(202, '您无权查看此书店数据'); //无权限访问
        }

        $shop_id = $this->request->shop_id;
        $keywords_type = $this->request->keywords_type;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        //     $settle_state = $this->request->settle_state;
        $book_selector = $this->request->book_selector;
        $way = $this->request->way;
        $pur_manage_id = $this->request->pur_manage_id;
        $settle_sponsor_manage_id = $this->request->settle_sponsor_manage_id;

        $param = [
            'shop_id' => $shop_id,
            'keywords_type' => $keywords_type,
            'keywords' => $keywords,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'book_selector' => $book_selector,
            'way' => $way,
            'type' => 1, //只算新书
            'pur_manage_id' => $pur_manage_id,
            'settle_sponsor_manage_id' => $settle_sponsor_manage_id,
            'shop_all_id' => $shop_all_id,
        ];
        $param['select_way'] = 4;
        $param['settle_state'] = null;
        $data['purchase_number'] = $this->bookHomePurchaseModel->lists($param); //总数量
        $param['settle_state'] = 3;
        $data['unfinal_number'] = $this->bookHomePurchaseModel->lists($param); //未结算数量
        $param['settle_state'] = 2;
        $data['finaling_number'] = $this->bookHomePurchaseModel->lists($param); //结算中数量
        $param['settle_state'] = 1;
        $data['final_number'] = $this->bookHomePurchaseModel->lists($param); //已结算数量


        $param['select_way'] = 3;
        $param['settle_state'] = null;
        $data['purchase_money'] = $this->bookHomePurchaseModel->lists($param); //总金额
        $param['settle_state'] = 3;
        $data['unfinal_money'] = $this->bookHomePurchaseModel->lists($param); //未结算金额
        $param['settle_state'] = 2;
        $data['finaling_money'] = $this->bookHomePurchaseModel->lists($param); //结算中金额
        $param['settle_state'] = 1;
        $data['final_money'] = $this->bookHomePurchaseModel->lists($param); //已结算金额

        return $this->returnApi(200, '获取成功', true, $data);
    }
    /**
     * 修改采购清单状态为 已结算
     * @param purchase_ids  采购清单id  多个 ，逗号拼接
     */
    public function purchaseStateModify()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('purchase_state_modify')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id)) {
            return $this->returnApi(202, '您无权操作此书店'); //无权限访问
        }

        $purchase_ids = $this->request->purchase_ids;
        $purchase_ids = explode(',', $purchase_ids);
        $res = $this->bookHomePurchaseModel->whereIn('id', $purchase_ids)->get();
        DB::beginTransaction();
        try {
            $ids = [];
            foreach ($res as $key => $val) {
                if ($val['settle_state'] != 2) {
                    continue;
                }
                $ids[] = $val['id'];
            }
            $this->bookHomePurchaseModel->whereIn('id', $ids)->update([
                'settle_state' => 1,
                'settle_affirm_time' => date('Y-m-d H:i:s'),
                'settle_affirm_manage_id' => $this->request->manage_id,
            ]);
            DB::commit();
            return $this->returnApi(200, '修改成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '修改失败');
        }
    }


    /**
     * 所有(新书)采购清单 (书店端查看)(线上)
     * @param shop_id  书店id   0、全部
     * @param keywords_type  检索条件   0、全部  1、书名  2、作者 3 ISBN 4 读者证号 5 条形码 默认 0
     * @param keywords  检索条件
     * @param start_time 申请开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 申请结束时间     数据格式    2020-05-12 12:00:00
     * @param is_return 是否归还   不传  或转空  或 0，表示全部  1 借阅中  2 已归还   3 归还中
     * @param is_overdue 是否逾期   不传  或转空  或 0，表示全部  1 未逾期  2 已逾期
     * @param pur_manage_id  采购管理员id  不传  或转空  或 0，表示全部
     * @param return_manage_id  归还书籍管理员id   不传  或转空  或 0，表示全部
     * @param book_selector  是否套书   不传  或转空  或 0，表示全部  1 是 2 否
     * @param node   是否借阅成功  0全部 1成功  2 失败
     * @param settle_state   结算状态  0、全部 1 已结算  2 结算中  3 未结算
     * @param way		采购方式   1 为 线上荐购 ， 2 为线下荐购
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function purchaseAllList()
    {
        $shop_all_id = $this->getAdminShopIdAll();
        if (empty($shop_all_id)) {
            return $this->returnApi(203, '您无权查看书店数据'); //无权限访问
        }
        $shop_id = $this->request->shop_id;
        $keywords_type = $this->request->keywords_type;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $is_return = $this->request->is_return;
        $is_overdue = $this->request->is_overdue;
        $settle_state = $this->request->settle_state;
        $pur_manage_id = $this->request->pur_manage_id;
        $return_manage_id = $this->request->return_manage_id;
        $node = $this->request->node;
        $way = $this->request->way;
        $page = intval($this->request->page, 1) ?: 1;
        $limit = intval($this->request->limit, 10) ?: 10;

        $param = [
            'shop_id' => $shop_id,
            'keywords_type' => $keywords_type,
            'keywords' => $keywords,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'settle_state' => $settle_state,
            'is_return' => $is_return,
            'is_overdue' => $is_overdue,
            'way' => $way,
            'node' => $node,
            'pur_manage_id' => $pur_manage_id,
            'return_manage_id' => $return_manage_id,
            'shop_all_id' => $shop_all_id,
            'page' => $page,
            'limit' => $limit,
            'select_way' => 1,
            'way' => 1, //1为线上
        ];
        //列表
        $res = $this->bookHomePurchaseModel->lists($param);

        if ($res['data']) {
            foreach ($res['data'] as $key => $val) {
                //计算逾期时间
                $res['data'][$key]['overdue_day'] = $this->bookHomePurchaseModel->getOverdueDayMoney($val);
            }
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }
}
